package com.example.switchingnetwork;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.switchingnetwork.util.HttpUtil;
import com.example.switchingnetwork.util.NetSwitchUtil;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private TextView textView;

    Button buttonWife;
    Button buttonData;
    Button buttonRetrofitGet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initEvent();

        HttpUtil httpUtil = new HttpUtil();
        httpUtil.forceSmsNetwork(this, network -> {
            if (network == null) {
                Log.i("----->", "network is null");
            } else {
                Log.i("----->", String.valueOf(network));
                sendRequestByOkhttp();
            }
        });
    }

    /**
     * 初始化控件
     */
    private void initView() {
        textView = findViewById(R.id.tv_show_message);
        buttonWife = findViewById(R.id.btn_switch_wifi);
        buttonData = findViewById(R.id.btn_switch_mobile_data);
    }

    /**
     * 初始化点击事件
     */
    private void initEvent() {

        // 判断 wifi 是否连接
        buttonWife.setOnClickListener(view -> {
            if (NetSwitchUtil.isWifiConnected(MainActivity.this)) {
                Toast.makeText(MainActivity.this, "wifi is connected", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "wifi is unconnected", Toast.LENGTH_SHORT).show();
            }
        });

        // 判断蜂窝网络是否连接
        buttonData.setOnClickListener(view -> {
            if (NetSwitchUtil.isMobileDataConnected(MainActivity.this)) {
                Toast.makeText(MainActivity.this, "mobile data is connected", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "mobile data is unconnected", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 网络请求
     */
    private void sendRequestByOkhttp() {
        new Thread(() -> {
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://www.baidu.com")
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                showResponse(responseData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(() -> textView.setText(response));
    }

}